import { useStore } from "vuex";
import { computed, watch, ref } from "vue";
import { getLyric } from "@/api/index";
import Lyric from "lyric-parser";
const lyricMap = {};
export default function useLyric({ songReady, currentTime }) {
  const currentLyric = ref(null); //当前歌词
  const currentLineNum = ref(0); //当前显示的歌词行号
  const pureMusicLyric = ref(0); //判断纯音乐
  const playingLyric = ref(""); //正在播放歌词
  const lyricScrollRef = ref(null);
  const lyricListRef = ref(null);
  const store = useStore();
  const currentSong = computed(() => store.getters.currentSong);
  watch(currentSong, async (newSong) => {
    if (!newSong.url || !newSong.id) {
      return;
    }
    const songId = newSong.id;
    let lyricResult = lyricMap[songId];
    if (!lyricResult) {
      const getLyricList = await getLyric(newSong);
      console.log(getLyricList);
      lyricResult = getLyricList.data.lrc.lyric;
      lyricMap[songId] = lyricResult;
    }
    store.commit("addSongLyric", {
      song: newSong,
      lyric: lyricResult,
    });
    //异步歌词在切换过程中可能出现不同
    if (currentSong.value.lyric !== lyricResult) {
      return;
    }
    currentLyric.value = new Lyric(lyricResult, handleLyric);
    const hasLyric = currentLyric.value.lines.length;
    if (hasLyric) {
      //歌曲准备好时播放歌词
      if (songReady.value) {
        playLyric();
      }
    } else {
      playingLyric.value = pureMusicLyric.value = "当前音乐为纯音乐";
    }
  });
  function handleLyric({ lineNum, txt }) {
    currentLineNum.value = lineNum;
    playingLyric.value = txt;
    const scrollComp = lyricScrollRef.value;
    const listEl = lyricListRef.value;
    if (!listEl) {
      return;
    }
    if (lineNum > 5) {
      const lineEl = listEl.children[lineNum - 5];
      scrollComp.scroll.scrollToElement(lineEl, 1000);
    } else {
      scrollComp.scroll.scrollToElement(0, 1000);
    }
  }
  //播放歌词
  function playLyric() {
    const currentLyricVal = currentLyric.value;
    if (currentLyricVal) {
      currentLyricVal.seek(currentTime.value * 1000);
    }
  }
  //暂停播放
  function stopLyric() {
    const currentLyricVal = currentLyric.value;
    if (currentLyricVal) {
      currentLyricVal.stop();
    }
  }
  return {
    currentLyric,
    currentLineNum,
    playLyric,
    playingLyric,
    lyricScrollRef,
    lyricListRef,
    stopLyric,
    pureMusicLyric,
  };
}
